<?php

namespace App\Http\Controllers;

use App\User;
use EasyWeChat\Factory;
use Illuminate\Http\Request;

class WechatController extends Controller
{
    private $app;
    public function __construct()
    {
        $this->app = getOfficialAccount();

    }

    //响应微信验证
    public function response(){

        $response = $this->app->server->serve();

        return $response;

    }

    //网页授权登陆
    public function wechatUserLogin(){
        $user = session('user');
        if(empty($user)){
            $response = $this->app->oauth->scopes(['snsapi_userinfo'])
                ->redirect(route('Wechat.user'));
            return redirect($response->getTargetUrl());
        }
        return redirect()->route('Booking.create');
    }


    public function getUserInfo(){
        $userInfo = $this->app->oauth->user();
        $openid = $userInfo->id;
        $result = User::firstWhere('openid',$openid);
        if($result === null){
            $result = User::create([
                'openid' => $openid,
                'info'   => serialize($userInfo)
            ]);
        }
        session(['user'=>$result]);
        return redirect()->route('Booking.create');
    }

}
